package com.jasmine.bjstkserver.manager.weather;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jasmine.core.constants.BjsConstants;
import com.jasmine.core.constants.enums.DictEnum;
import com.jasmine.bjstkserver.server.dict.DictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : jasmineXz
 */
@Component
public class WeatherManager {
    private static final Logger log = LoggerFactory.getLogger(WeatherManager.class);

    @Autowired
    private DictService dictService;

    private static final String URL_NOW    = "https://devapi.heweather.net/v7/weather/now";
    private static final String URL_DAILY  = "https://devapi.heweather.net/v7/weather/3d";
    private static final String URL_HOURLY = "https://devapi.heweather.net/v7/weather/24h";

    /**
     * HeWeatherDTO
     */
    @Cacheable(cacheNames = BjsConstants.Redis.WEATHER_ALL, key = "'location_' + #location")
    public HeWeatherDTO findWeatherAll (String location,Integer userId) {
        Map<String,Object> maps = initParam(location,userId);
        HttpResponse now     = HttpRequest.get(URL_NOW).form(maps).execute();
        HttpResponse daily   = HttpRequest.get(URL_DAILY).form(maps).execute();
        HttpResponse hourly  = HttpRequest.get(URL_HOURLY).form(maps).execute();

        JSONObject nowJson    = JSONUtil.parseObj(now.body());
        JSONObject dailyJson  = JSONUtil.parseObj(daily.body());
        JSONObject hourlyJson = JSONUtil.parseObj(hourly.body());

        HeWeatherDTO weather = new HeWeatherDTO();

        // 1. 当前时间
        if ("200".equals(nowJson.getStr("code"))) {
            HeWeatherDTO.Now heNow = JSONUtil.toBean(nowJson.getJSONObject("now"),HeWeatherDTO.Now.class);
            heNow.setIconValue(HeCondCode.getIcon(heNow.getIcon()));
            weather.setNow(heNow);
        } else {
            log.error("获取当天气失败,body : [{}]",nowJson.toString());
        }

        // 2. 天气预报
        if ("200".equals(dailyJson.getStr("code"))) {
            List<HeWeatherDTO.Daily> daily3D = JSONUtil.toList(dailyJson.getJSONArray("daily"),HeWeatherDTO.Daily.class);
            for (int i = 0; i < 3; i++) {
                daily3D.get(i).setIconValueDay(HeCondCode.getIcon(daily3D.get(i).getIconDay()));
                daily3D.get(i).setIconValueNight(HeCondCode.getIcon(daily3D.get(i).getIconNight()));
            }
            weather.setDaily(daily3D);
        } else {
            log.error("获取3日天气预报失败,body : [{}]",dailyJson.toString());
        }

        // 3. 小时预报
        if ("200".equals(hourlyJson.getStr("code"))) {
            List<HeWeatherDTO.Hourly> originalHourly   = JSONUtil.toList(hourlyJson.getJSONArray("hourly"),HeWeatherDTO.Hourly.class);
            List<HeWeatherDTO.Hourly> newHourly = new ArrayList<>();
            newHourly.add(originalHourly.get(0));
            for (int i = 0; i < 1; i++) {
                newHourly.get(i).setIconValue(HeCondCode.getIcon(newHourly.get(i).getIcon()));
            }
            weather.setHourly(newHourly);
        } else {
            log.error("获取小时预报失败,body : [{}]}",hourlyJson.toString());
        }

        return weather;
    }


    /**
     * 查询当前时间
     * @param userId 用户ID
     */
    @Cacheable(cacheNames = BjsConstants.Redis.WEATHER_NOW, key = "'location_' + #location")
    public HeWeatherDTO.Now findNow(String location,Integer userId) {
        return null;
    }


    /**
     * 查询天气预报
     * @param userId 用户ID
     */
    @Cacheable(cacheNames = BjsConstants.Redis.WEATHER_FORECAST, key = "'location_' + #location")
    public List<HeWeatherDTO.Daily> findForecast(String location,Integer userId) {
        return null;
    }


    /**
     * 查询逐小时预报
     * @param userId 用户ID
     */
    @Cacheable(cacheNames = BjsConstants.Redis.WEATHER_HOURLY, key = "'location_' + #location")
    public List<HeWeatherDTO.Hourly> findHourly(String location,Integer userId) {
        return null;
    }



    /**
     * 清除缓存
     */
    @CacheEvict(cacheNames = BjsConstants.Redis.WEATHER_ALL, key = "'location_' + #location")
    public void clearAll (String location,Integer userId) {

    }
    /**
     * 清除缓存
     */
    @CacheEvict(cacheNames = BjsConstants.Redis.WEATHER_NOW, key = "'location_' + #location")
    public void clearNow (String location,Integer userId) {

    }
    /**
     * 清除缓存
     */
    @CacheEvict(cacheNames = BjsConstants.Redis.WEATHER_FORECAST, key = "'location_' + #location")
    public void clearForecast (String location,Integer userId) {

    }
    /**
     * 清除缓存
     */
    @CacheEvict(cacheNames = BjsConstants.Redis.WEATHER_FORECAST, key = "'location_' + #location")
    public void clearHourly (String location,Integer userId) {

    }

    /**
     * 获取参数
     * @param userId 用户ID
     * @return 返回查询参数
     */
    private Map<String,Object> initParam(String location,Integer userId) {
        userId = null == userId ? 1 : userId;
        Map<String,Object> map = new HashMap<>(2);
        map.put("location",getLocation(location,userId));
        map.put("key",getKey(userId));
        return map;
    }


    public static final String HEFENG_DICT_ID = "5010";
    private static final String HEFENG_DICT_KEY = "KEY";
    public static final String HEFENG_DICT_LOCATION = "LOCATION";

    /**
     * 获取和风key
     * @param userId 用户ID
     * @return 和风key
     */
    private String getKey (Integer userId) {
        return dictService.getDictValue(DictEnum.WEATHER_HE.code(),HEFENG_DICT_KEY,userId);
    }

    /**
     * 获取和风地址
     * @param userId 用户ID
     * @return 用户地址
     */
    private String getLocation (String location,Integer userId) {
        return null == userId ? location : dictService.getDictValue(DictEnum.WEATHER_HE.code(),HEFENG_DICT_LOCATION,userId);
    }


    public static void main(String[] args) {

        Map<String,Object> map = new HashMap<>(2);
        map.put("location","hangzhou");
        map.put("key","");

        HttpResponse response = HttpRequest.get(URL_HOURLY).form(map).execute();
        JSONObject jsonObject = JSONUtil.parseObj(response.body());
        System.out.println(jsonObject.getJSONArray("HeWeather6").toString());
        List<HeWeatherDTO> list = JSONUtil.toList(jsonObject.getJSONArray("HeWeather6"),HeWeatherDTO.class);

        list.get(0);
    }


}
